package com.fly.locks.thread.adder;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.util.StopWatch;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LongAdderThread implements Runnable
{
    private LongAdder count = new LongAdder();
    
    @Override
    public void run()
    {
        if (count.sum() >= 5)
        {
            log.info("请求用户过多,请稍后再试! 计数器：{}", count.sum());
            return;
        }
        try
        {
            count.increment();
            log.info("业务处理开始,计数器自增：{}", count.sum());
            
            // 模拟耗时业务操作
            log.info("★★★★★★★★ 报名或抢购处理中★★★★★★★★");
            StopWatch clock = new StopWatch();
            clock.start();
            TimeUnit.MILLISECONDS.sleep(RandomUtils.nextInt(10000, 20000));
            clock.stop();
            log.info("运行 {} ms ---------------", clock.getLastTaskTimeMillis());
        }
        catch (InterruptedException e)
        {
            log.error(e.getMessage());
        }
        finally
        {
            count.decrement();
            log.info("业务处理完毕,计数器自减：{}", count.sum());
        }
    }
    
}